/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.datasource;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.util.StringUtils;
import org.tianyun.cloud.config.refresh.smart.SmartBeanDefinition;
import org.tianyun.cloud.datasource.routing.DataSourceFactory;

import java.util.Map;

/**
 * RabbitMQ装载配置器
 *
 * @auther ebert_chan
 */
public class DataSourceFactoryConfigurer {

    private static final String DATASOURCE_CLUSTER_NAME_SUFFIX = ".dataSourceFactory";

    private DataSourceFactoryBeanWrapper dataSourceFactoryBeanWrapper;

    public DataSourceFactoryConfigurer(String propertyBeanName, Map<String, Object> attributes) {
        dataSourceFactoryBeanWrapper = new DataSourceFactoryBeanWrapper();
        dataSourceFactoryBeanWrapper.setPropertyBeanName(propertyBeanName);
        dataSourceFactoryBeanWrapper.setDataSourceFactoryBeanName((String) attributes.get("datasource"));
        dataSourceFactoryBeanWrapper.setRefreshKey((String) attributes.get("prefix"));
        if (!StringUtils.hasText(dataSourceFactoryBeanWrapper.getDataSourceFactoryBeanName())) {
            // 自动定义一个beanName
            dataSourceFactoryBeanWrapper.setDataSourceFactoryBeanName(propertyBeanName + DATASOURCE_CLUSTER_NAME_SUFFIX);
        }
    }

    public DataSourceFactoryBeanWrapper getDataSourceFactoryBeanWrapper() {
        return dataSourceFactoryBeanWrapper;
    }

    public void registryBean(BeanDefinitionRegistry registry) {
        if (!registry.containsBeanDefinition(dataSourceFactoryBeanWrapper.getPropertyBeanName())) {
            return;
        }

        BeanDefinition dataSourceFactory = this.dataSourceFactoryBeanDefinition(dataSourceFactoryBeanWrapper.getDataSourceFactoryBeanName(), dataSourceFactoryBeanWrapper.getPropertyBeanName());
        // 使用SmartBeanDefinition，根据refreshKey动态刷新
        SmartBeanDefinition proxyCachingConnectionFactory = new SmartBeanDefinition(dataSourceFactoryBeanWrapper.getRefreshKey(), dataSourceFactory);
        proxyCachingConnectionFactory.registerBeanDefinition(registry, dataSourceFactoryBeanWrapper.getDataSourceFactoryBeanName());
    }

    private BeanDefinition dataSourceFactoryBeanDefinition(String dataSourceFactoryBeanName, String propertyBeanName) {
        // @formatter:off
		BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(DataSourceFactory.class)
                .addConstructorArgValue(dataSourceFactoryBeanName)
                .addConstructorArgReference(propertyBeanName);
		// @formatter:on
        return builder.getBeanDefinition();
    }

}
